<?php
/**
 * CalendarModel handles the database interactions for calendar/event actions
 *  
 * author: Jimmy E. Lewis
 */
class CalendarModel extends Model {
	
	function __construct() {
		parent::__construct();
		$this->load->helper('date');		
	}
	
	
	/**
	 * Creates a calendar event with post data.
	 */
	function createEvent($post) {
		$this->db->insert('events',$post);
	}
	
	function getEventForItem($id){
		$this->db->select('event_id')->from('items')->where('id',$id);
		$event = $this->db->get()->row();
		$this->db->select('*')->from('events')->where('id',$event->event_id);
		return $this->db->get()->row();
	}
	
	function assignItem($id,$post){
		$this->db->where('id', $id);
		$this->db->update('items',$post);
	}
	
	function createitem($post) {
		$this->db->insert('items',$post);
	}
	
	/**
	 * Updates a given calendar event with post data.
	 */
	function updateEvent($id, $post) {
		$this->db->where('id', $id);
		$this->db->update('events', $post);
	}
	
	/**
	 * Deletes a given calendar event.
	 */
	function deleteEvent($id){
		$this->db->where('id',$id);
		$this->db->delete('events');
		
		//also delete all items for this event;
		$items = $this->getItems($id);
		if ($items->num_rows() > 0) {
			foreach ($items->result() as $row) {
				$this->deleteItem($row->id);
			}
		}
	}
	
	/**
	 * Deletes a given item.
	 */
	function deleteItem($id){
		$this->db->where('id',$id);
		$this->db->delete('items');
	}
	
	/**
	 * Get calendar events between given unix timestamps.
	 */
	function getEvents($start,$end){
		$start = date('Y-m-d H:i:s',$start);
		$end = date('Y-m-d H:i:s',$end);
		
//		echo $start . ' ' . $end;
		
		$where = "(start >='$start' AND end <='$end') OR (start <= '$end' AND end >= '$start')";
		
		$this->db->select('*')->from('events')->where($where)->orderby('start','asc');
//		echo "<br>" . $this->db->last_query() . "<br>";
		return $this->db->get();
	}
	
	/**
	 * Gets all calendar events
	 */
	function getAll(){
		$this->db->select('*')->from('events')->orderby('start','asc');
		return $this->db->get();
		
	}
	
	/**
	 * Gets event with the given id number.
	 */
	function getEvent($id){
		$this->db->select('*')->from('events')->where('id',$id);
		return $this->db->get()->row();
		
	}
	
	function getItem($id){
		$this->db->select('*')->from('items')->where('id',$id);
		return $this->db->get()->row();
		
	}
	
	/**
	 * Gets items with the given event id number.
	 */
	function getItems($id){
		$this->db->select('*')->from('items')->where('event_id',$id)->orderby('name','asc');
		return $this->db->get();
	}
	
	function getRVSP($eventId,$type){
		
	}
	
}